package cn.wj.school.cloud.utils;

import cn.wj.school.cloud.dto.SyUserDTO;
import cn.wj.school.cloud.security.SecurityAuthentication;
import cn.wj.school.cloud.security.SecurityContextHolder;
import cn.wj.school.cloud.security.context.SecurityContext;

import javax.servlet.http.HttpSession;

public class SecurityUtils {
    /**
     * 取得当前用户的登录名,就是用户code， 如果当前用户未登录则返回空字符串.
     */
    public static String getCurrentUserCode() {
        SecurityAuthentication user = getAuthentication(null);
        return user == null ? "" : user.getUserCode();
    }

    /**
     * 取得当前用户的登录名,用户描述 如果当前用户未登录则返回空字符串.
     */
    public static String getCurrentUserText() {
        SyUserDTO user = getCurrentUser();
        return user == null ? "" : user.getUserName();
    }

    /**
     * 取得当前用户的登录名,用户描述 如果当前用户未登录则返回空字符串.
     */
    public static String getCurrentUserType() {
        SyUserDTO user = getCurrentUser();
        return user == null ? "" : user.getType();
    }

    /**
     * 取得当前用户, 返回值为User类
     */
    public static SyUserDTO getCurrentUser() {

        SecurityAuthentication authentication = getAuthentication(null);

        if (authentication == null) {
            return null;
        }

        Object principal = authentication.getPrincipal();
        if (!(principal instanceof SyUserDTO)) {
            return null;
        }
        return (SyUserDTO) principal;

    }

    public static SyUserDTO getCurrentUser(HttpSession session) {

        SecurityAuthentication authentication = getAuthentication(session);

        if (authentication == null) {

            return null;
        }

        Object principal = authentication.getPrincipal();
        if (!(principal instanceof SyUserDTO)) {
            return null;
        }
        return (SyUserDTO) principal;

    }

    /**
     * 取得Authentication, 如当前SecurityContext为空时返回null.
     */
    public static SecurityAuthentication getAuthentication(HttpSession session) {

        SecurityContext context = null;
        // 从session获取
        if (session != null) {
            context = (SecurityContext) session.getAttribute(SecurityContextHolder.SECURITY_CONTEXT);
        } else {
            context = SecurityContextHolder.getContext();
        }
        if (context == null) {
            return null;
        }

        return context.getAuthentication();
    }
}
